const app = getApp();

Page({
  data: {
    userInfo: null,
    loading: true
  },

  onShow() {
    this.loadUserInfo();
  },

  async loadUserInfo() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.setData({
        userInfo: null,
        loading: false
      });
      return;
    }

    try {
      const res = await app.request({
        url: '/member/profile/',
        method: 'GET'
      });

      if (res.code === 200) {
        this.setData({
          userInfo: res.data,
          loading: false
        });
      }
    } catch (error) {
      console.error('获取用户信息失败：', error);
      if (error.statusCode === 401) {
        // token失效，清除登录状态
        wx.removeStorageSync('token');
        wx.removeStorageSync('userInfo');
        this.setData({
          userInfo: null
        });
      }
    } finally {
      this.setData({ loading: false });
    }
  },

  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  goToProfile() {
    wx.navigateTo({
      url: '/pages/member/profile/profile'
    });
  },

  goToOrders(e) {
    const status = e.currentTarget.dataset.status;
    wx.navigateTo({
      url: `/pages/order/list/list${status ? '?status=' + status : ''}`
    });
  },

  goToAllOrders() {
    wx.navigateTo({
      url: '/pages/order/list/list'
    });
  },

  goToAddress() {
    wx.navigateTo({
      url: '/pages/address/list/list'
    });
  },

  goToSettings() {
    wx.navigateTo({
      url: '/pages/member/settings/settings'
    });
  },

  async handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          this.setData({
            userInfo: null
          });
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  }
}); 